package com.atjinggu.jinggumail.member.interceptor;

import com.atjinggu.jinggumail.common.constant.AuthConstant;
import com.atjinggu.jinggumail.common.vo.MemberResponseVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jingming
 * @Type LoginInterceptor.java
 * @Desc
 * @date 2021/3/7 21:10
 */
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<MemberResponseVo>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        boolean match = new AntPathMatcher().match("/member/member/login", request.getRequestURI());
        if(match){
            return true;
        }
        boolean match1 = new AntPathMatcher().match("/member/memberreceiveaddress/**", request.getRequestURI());

        if(match1){
            return true;
        }
        MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if(null != attribute){
            loginUser.set(attribute);
            return true;
        }
        request.getSession().setAttribute("errorMsg","请先登陆！");
        response.sendRedirect("http://oauth.jinggumail.com/login.html");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        loginUser.remove();
    }
}